package com.binguo.api.baidu;

import com.binguo.api.baidu.model.BaiduSearchResult;
import com.binguo.api.service.RedisLockService;
import com.binguo.api.webapi_tts.FileUtil;
import com.binguo.common.util.JsonUtil;
import com.binguo.youtu.sign.Base64Util;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Component
public class BaiduUtil {

    private static String appid = "16805085";
    private static String apiKey = "3t7PQUPeThDcPyEpUNh8UHZA";
    private static String securityKey = "SciYNqyHOip2GnS5jDjw5nCgeaqFA85w";

    private static String tokenKey = "baiduToken";
    private static Long tokenExpireTime = 0l;

    @Autowired
    private RedisLockService redisLockService;

    public String getBaiduToken(Integer shopId){
        Object tokenObj = redisLockService.getKey(tokenKey + shopId);

        if (tokenObj == null) {
            String token = getAuth(apiKey, securityKey);

            token = URLEncoder.encode(token);
            redisLockService.setKey(tokenKey + shopId, token, tokenExpireTime - 5000);

            return token;
        }else {
            return tokenObj.toString();
        }

    }

    public boolean addImg(Integer shopId, String filename, String tag) throws Exception{

        String token = getBaiduToken(shopId);

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=" + token;

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&sub_lib=" + appid + "&brief=" + tag;

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());
            /**
             * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
             */

            Map<String, String> m = JsonUtil.parse(result.getBody(), Map.class);

            if (StringUtils.hasText((String)m.get("cont_sign"))) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public void delImg(){

    }

    public BaiduSearchResult searchImg(Integer shopId, String filename) throws Exception{
        String token = getBaiduToken(shopId);

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + token;

        filename = "/Users/jay/IdeaProjects/binguo/api/target/1563161370392.jpg";
//        String filename = "/Users/jay/IdeaProjects/binguo/api/target/1562679047195.jpg";

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&top_num=" + 5;


        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            System.out.println(result.getBody());

            BaiduSearchResult baiduSearchResult = JsonUtil.parse(result.getBody(), BaiduSearchResult.class);

            return baiduSearchResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            tokenExpireTime = jsonObject.getLong("expires_in");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

}
